package com.p2p.backend.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jodd.util.StringUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.MyPage;
import com.p2p.base.util.DateUtil;
import com.p2p.base.util.biz.ModelViewUtil;
import com.p2p.front.web.form.AccountFreezeQueryForm;
import com.p2p.front.web.form.AccountQueryForm;
import com.p2p.trans.client.enums.AccountTypeEnum;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.model.AccountFreezeLogQueryDto;
import com.p2p.trans.client.model.AccountLogQueryDto;
import com.p2p.trans.client.result.AccountQueryResult;

/**
 * @author ruiqi
 *
 */
@RequestMapping("/account")
@Controller
public class AccountQueryController {

	/** Logger */
	private static final Logger logger = LoggerFactory
			.getLogger(AccountQueryController.class);

	@Resource
	private AccountQueryFacade accountQueryFacade;

	@RequestMapping("/viewBalanceByUserId")
	public String viewBalanceByUserId(ModelMap map, String userId) {

		String accountNo = "1788" + "0"
				+ AccountTypeEnum.INVESTORS_ACCOUNT.getCode() + userId + "0"
				+ "156";
		AccountQueryResult result = accountQueryFacade
				.getAccountInfo(accountNo);

		if (!result.isSuccess()) {
			map.addAttribute("res", 0);
			map.addAttribute("msg", "账户不存在");
		}
		map.addAttribute("res", 1);
		Map<String, Object> date = new HashMap<String, Object>();
		map.addAttribute("data", date);

		List<String> nameList = new ArrayList<String>();
		nameList.add("accountNo");
		nameList.add("balance");
		nameList.add("freezeAmount");
		nameList.add("canUserBalance");

		date.put("accountInfo",
				ModelViewUtil.getMapModelView(result.getAccountVO(), nameList));

		return "account/viewBalance";
	}

	@RequestMapping("/viewBalance")
	public String viewBalance(ModelMap map, String accountNo) {

		AccountQueryResult result = accountQueryFacade
				.getAccountInfo(accountNo);

		if (!result.isSuccess()) {
			map.addAttribute("res", 0);
			map.addAttribute("msg", "账户不存在");
		}
		map.addAttribute("res", 1);
		Map<String, Object> date = new HashMap<String, Object>();
		map.addAttribute("data", date);

		List<String> nameList = new ArrayList<String>();
		nameList.add("accountNo");
		nameList.add("balance");
		nameList.add("freezeAmount");
		nameList.add("canUserBalance");

		date.put("accountInfo",
				ModelViewUtil.getMapModelView(result.getAccountVO(), nameList));

		return "account/viewBalance";
	}

	@RequestMapping("/viewRechargeLog")
	public String viewLog(ModelMap map) {
		return "account/viewRechargeLog";
	}

	@RequestMapping("/viewWithdrawLog")
	public String viewWithdrawLog(ModelMap map) {
		return "account/viewWithdrawLog";
	}

	private AccountLogQueryDto form2Dto(AccountQueryForm form) {

		AccountLogQueryDto dto = new AccountLogQueryDto();
		Long minLogId = null;
		if (form.getStartDate() != null
				&& StringUtils.isNotBlank(form.getStartDate())) {
			// String startDateStr =
			// DateUtil.getYYYYMMDDStr(form.getStartDate());
			// String minLogIdStr = String.format("%09d",startDateStr);
			Date startDate = null;
			try {
				startDate = DateUtil.parseStandardDate(form.getStartDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String startDateStr = DateUtil.getYYYYMMDDStr(startDate);
			String minLogIdStr = startDateStr + "000000000";
			minLogId = Long.valueOf(minLogIdStr);
		}

		Long maxLogId = null;
		if (form.getEndDate() != null
				&& StringUtils.isNotBlank(form.getEndDate())) {
			Date endDate = null;
			try {
				endDate = DateUtil.parseStandardDate(form.getEndDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}

			String endDateStr = DateUtil.getYYYYMMDDStr(endDate);
			String maxLogIdStr = endDateStr + "999999999";
			maxLogId = Long.valueOf(maxLogIdStr);
		}

		// 拷贝查询条件
		dto.setMinLogId(minLogId);
		dto.setMaxLogId(maxLogId);
		/*if (StringUtils.isNoneBlank(form.getTransCode())) {
			dto.setTransCode(form.getTransCode());
		}*/
		if(StringUtils.isNotBlank(form.getTransCode())){
			if(form.getTransCode().length()>4){
				dto.setSubTransCode(form.getTransCode());
			}else{
				dto.setTransCode(form.getTransCode());
			}
		}
		
		// 拷贝分页条件
		dto.setPageSize(form.getPageSize());
		dto.setPageNum(form.getPageNum());

		return dto;
	}

	@RequestMapping("/viewLog")
	public void viewLog(Model model, String start, String end,
			String accountNo, String transCode, int page, int rows) {

		AccountQueryForm accountQueryForm = new AccountQueryForm();
		accountQueryForm.setStartDate(start);
		accountQueryForm.setEndDate(end);
		accountQueryForm.setPageNum(page);
		accountQueryForm.setPageSize(rows);
		accountQueryForm.setTransCode(transCode);
		AccountLogQueryDto accountLogQueryDto = form2Dto(accountQueryForm);

		accountLogQueryDto.setTransAccount(accountNo);

		MyPage result = accountQueryFacade
				.queryLogPageByConditions(accountLogQueryDto);

		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", result.getTotal());
		List<String> nameList = new ArrayList<String>();
		nameList.add("accountLogId");	
		nameList.add("transAmount");
		nameList.add("transDt");
		nameList.add("otherAccount");
		nameList.add("balance");
		nameList.add("transMemo");
		List mapModelViewList = ModelViewUtil.getMapModelViewList(result.getList(), nameList);
		data.put("rows",
				mapModelViewList);

		model.addAttribute("data", data);
	}

	@RequestMapping("/viewFreezeLog")
	public String viewFreezeLog(String accountNo,ModelMap model,
			AccountFreezeQueryForm accountFreezeQueryForm) {
		AccountFreezeLogQueryDto accountFreezeLogQueryDto = form2Dto(accountFreezeQueryForm);
		accountFreezeLogQueryDto.setAccountNo(accountNo);
	
		AccountQueryResult result = accountQueryFacade
				.queryFreezeLogPageByConditions(accountFreezeLogQueryDto);
		if (result.isSuccess()) {
			AccountFreezeLogQueryDto accountFreezeLogQueryDto2 = result
					.getAccountFreezeLogQueryDto();	
			model.addAttribute("res", 1);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("total", accountFreezeLogQueryDto2.getTotalCount());
			
			List<String> nameList = new ArrayList<String>();
			nameList.add("id");
			nameList.add("amount");
			nameList.add("freezeType");
			nameList.add("gmtCreate");
			nameList.add("totalFreezeAmount");
			List<Map<String, Object>> mapModelViewList = ModelViewUtil.getMapModelViewList(accountFreezeLogQueryDto2.getAccountFreezeLogList(), nameList);
			data.put("rows",
					mapModelViewList);
			
			model.addAttribute("data", data);
		}

		model.addAttribute("accountQueryForm", accountFreezeQueryForm);

		return "account/viewFreezeLog";
	}

	private AccountFreezeLogQueryDto form2Dto(AccountFreezeQueryForm form) {
		AccountFreezeLogQueryDto dto = new AccountFreezeLogQueryDto();
		try {
			if(StringUtils.isNotBlank(form.getStart())){
				dto.setStartTime(DateUtil.parseStandardDate(form.getStart()));
			}
			if(StringUtils.isNotBlank(form.getEnd())){
				dto.setEndTime(DateUtil.parseStandardDate(form.getEnd()));
			}
		} catch (ParseException e) {
			logger.error("date format error", e);
			throw new RuntimeException(e);
		}
		// 拷贝分页条件
		dto.setLimit(form.getPageSize());
		dto.setPgNumber(form.getPageNum());

		return dto;
	}
}
